import { createRouter, createWebHashHistory } from 'vue-router';
import Layout from '@/layout';
import { useStore } from 'vuex';
const routes = [
  {
    path: '/',
    name: 'home',
    component: () => import('@/views/HomeView.vue'),
    meta: {
      title: '首页',
    },
  },
  {
    path: '/imgs',
    name: 'imgs',
    component: () => import('../views/ImagesView.vue'),
    meta: {
      title: '分类新闻',
    },
  },
  {
    path: '/message',
    name: 'message',
    component: () => import('../views/MessageBoard.vue'),
    meta: {
      title: '留言板',
    },
  },
  {
    path: '/about',
    name: 'about',
    component: () => import('../views/AboutView.vue'),
    meta: {
      title: '我的',
      requiresAuth: true, 
    },
  },
  {
    path: '/textDetail',
    name: 'textDetail',
    component: () => import('../views/TextDetail.vue'),
    meta: {
      title: '详情',
    },
  },
  {
    path: '/imageDetail',
    name: 'imageDetail',
    component: () => import('../views/ImageDetail.vue'),
    meta: {
      title: '详情',
    },
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../layout/LoginView.vue'),
    meta: {
      title: '登录',
    },
  },
  {
    path: '/forgot-password',
    name: 'forgotpassword',
    component: () => import('../layout/ForgotPassword.vue'),
    meta: {
      title: '忘记密码',
    },
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../layout/Register.vue'),
    meta: {
      title: '注册密码',
    },
  },
  {
    path: '/userhome',
    name: 'userhome',
    component: () => import('../layout/UserHomeView.vue'),
    meta: {
      title: '退出登录',
    },
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

function useAuthStore() {
  const store = useStore();
  return { isLoggedIn: store.getters.isLoggedIn };
}

router.beforeEach((to, from, next) => {
  const authStore = useAuthStore();
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!authStore.isLoggedIn) {
      next({
        path: '/login',
        query: { redirect: to.fullPath },
      });
    } else {
      next();
    }
  } else {
    next();
  }
});
export default router;